package com.cloudsea.yunhaistores.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.cloudsea.yunhaistores.entity.MerchantUsers;
import com.cloudsea.yunhaistores.mapper.MerchantUsersMapper;
import com.cloudsea.yunhaistores.mapper.PaymentOrdersMapper;
import com.cloudsea.yunhaistores.service.DashboardService;
import com.cloudsea.yunhaistores.vo.DashboardSummaryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired private PaymentOrdersMapper paymentOrdersMapper;
    @Autowired private MerchantUsersMapper merchantUsersMapper;

    @Override
    public DashboardSummaryVO getTodaySummary() {
        // 1. 安全校验：获取当前登录用户的商户ID
        long loginId = StpUtil.getLoginIdAsLong();
        MerchantUsers currentUser = merchantUsersMapper.selectById(loginId);
        if (currentUser == null || currentUser.getMerchantId() == null) {
            throw new SecurityException("无法获取当前商户信息");
        }
        Long merchantId = currentUser.getMerchantId();

        // 2. 定义今天的时间范围
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN); // 今天 00:00:00
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);   // 今天 23:59:59

        // 3. 调用Mapper的自定义方法进行查询
        DashboardSummaryVO summary = paymentOrdersMapper.getDashboardSummary(merchantId, todayStart, todayEnd);

        // 4. 计算平均客单价
        if (summary.getTotalOrders() > 0) {
            summary.setAverageOrderValue(summary.getTotalTurnover() / summary.getTotalOrders());
        }

        return summary;
    }
}